package com.monkey.netty.chapter2;

import java.nio.charset.Charset;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LoggingHandler;

/**
 * netty服务端启动
 * 
 * @author monkeychen
 *
 */
public class NettyServerStart {

	public static void main(String[] args) {
		// 1、实例化服务端启动入口
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		// 2、创建Reactor主线程程，用于接收客户端连接
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		// 3、创建Reactor从线程池，用于SocketChannel的读写和异常操作
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		// 4、设置Reactor主从线程池
		serverBootstrap.group(bossGroup, workerGroup)
				// 5、指定服务端通道类型NioServerSocketChannel
				.channel(NioServerSocketChannel.class)
				// 6、设置NioServerSocketChannel的TCP连接参数
				.option(ChannelOption.SO_BACKLOG, 1024)
				// 7、设置NioSocketChannel的TCP连接参数
				.childOption(ChannelOption.TCP_NODELAY, true)
				// 8、设置ServerSocketChannel的处理器
				.handler(new LoggingHandler())
				// 9、设置SocketChannel的处理器
				.childHandler(new ChannelInitializer<Channel>() {
					@Override
					protected void initChannel(Channel channel) throws Exception {
						channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
						channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
							@Override
							protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
								// 打印客户端的消息
								System.out.println(msg);
							}
						});
					}
				});
		try {
			// 10、绑定端口
			ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
			channelFuture.addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					System.out.println("服务端启动成功!");
				}
			});
			// 11、一直阻塞直到Server socket 关闭
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			// 12、优雅关闭线程池
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
